package com.qw.badge.sample

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by qinwei on 2021/6/20 4:21 下午
 * email: qinwei_it@163.com
 */
object Badge {
    private val supportBadges = ArrayList<Class<out IBadge>>()
    private val badgeLaunchers = HashMap<Class<out IBadge>, ArrayList<String>>()

    init {
        supportBadges.add(XiaomiBadge::class.java.apply {
            badgeLaunchers[this] = ArrayList<String>().apply {
                add("com.miui.home")
            }
        })
        supportBadges.add(VIVOBadge::class.java.apply {
            badgeLaunchers[this] = ArrayList<String>().apply {
                add("com.vivo.launcher")
                add("com.bbk.launcher2")
            }
        })
        supportBadges.add(HuaweiBadge::class.java.apply {
            badgeLaunchers[this] = ArrayList<String>().apply {
                add("com.huawei.android.launcher")
            }
        })
        supportBadges.add(OppoBadge::class.java.apply {
            badgeLaunchers[this] = ArrayList<String>().apply {
                add("com.oppo.launcher")
            }
        })
    }

    fun setBadgeNum(context: Context, num: Int) {
        val homePackage = getHomePackage(context)
        for (supportBadge in supportBadges) {
            if (badgeLaunchers[supportBadge]?.contains(homePackage) == true) {
                val badge = supportBadge.newInstance()
                badge.setBadgeNum(context, num)
                return
            }
        }
    }

    fun getHomePackage(context: Context): String {
        context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return ""
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_HOME)
        //Turns out framework does not guarantee to put DEFAULT Activity on top of the list.
        val resolveInfoDefault: ResolveInfo =
            context.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)
                ?: return ""
        return resolveInfoDefault.activityInfo.packageName
    }
}